package com.fyzk.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import http.DataUtil.text.TextUtil;

/**
 * <p>
 *
 * @author 指尖沙漏
 * </p>
 * @mood
 * @description 字符串操作工具类
 * @date 2017/8/24 0024 下午 4:02
 */
public class StringUtils {

    /**
     * 正则：身份证号码18位
     */
    public static final String REGEX_ID_CARD = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";

    /**
     * 正则表达式：验证手机号
     */
    public static final String REGEX_MOBILE = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";

    /**
     * 正则表达式：验证手密码 6-16位字母和数字组合
     */
    public static final String REGEX_PASSWORD_NUM_LETTER = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";

    /**
     * 正则表达式：验证手密码 6-16位字母或数字
     */
    public static final String REGEX_PASSWORD = "^[0-9A-Za-z]{6,16}$";

    /**
     * 正则表达式：验证邮箱
     * "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    /**
     * 正则表达式：验证汉字
     */
    public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$";

    /**
     * 正则表达式：验证是否为纯数字
     */
    public static final String REGEX_NUMBER = "[0-9]+";

    /**
     * 正则表达式：验证是否为纯字母
     */
    public static final String REGEX_LETTER = "[a-zA-Z]+";

    /**
     * 校验18位身份证号码
     *
     * @param idCard
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isIdCard(String idCard) {
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }

    /**
     * 校验手机号
     *
     * @param mobile
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isMobile(String mobile) {
        return Pattern.matches(REGEX_MOBILE, mobile);
    }

    /**
     * 校验密码
     *
     * @param pwd
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isPassword(String pwd) {
        return Pattern.matches(REGEX_PASSWORD, pwd);
    }

    /**
     * 校验密码
     *
     * @param pwd
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isNumAndLetterPassword(String pwd) {
        return Pattern.matches(REGEX_PASSWORD_NUM_LETTER, pwd);
    }

    /**
     * 校验邮箱
     *
     * @param email
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

    /**
     * 校验汉字
     *
     * @param chinese
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isChinese(String chinese) {
        return Pattern.matches(REGEX_CHINESE, chinese);
    }

    /**
     * 校验数字
     *
     * @param num
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isNumber(String num) {
        return Pattern.matches(REGEX_NUMBER, num);
    }

    /**
     * 校验字母
     *
     * @param num
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isLetter(String num) {
        return Pattern.matches(REGEX_LETTER, num);
    }

    /**
     * 检测String是否全是中文
     *
     * @param name
     * @return
     */
    public static boolean checkNameChinese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() < 1 || "null".equals(str.trim());
    }

    /**
     * 生成UUID
     */
    public static String getUuid() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    /**
     * 获取IP地址
     *
     * @param context
     * @return
     */
    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }
            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * 小数点后保留两位
     *
     * @param price
     */
    public static String getPrice(String price) {
        DecimalFormat format = new DecimalFormat("0.00");
        String a = "0.00";
        try {
            a = format.format(new BigDecimal(price.replace(",", "")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }

    /**
     * 小数点后保留1位
     *
     * @param price
     */
    public static String getMinPrice(String price) {
        DecimalFormat format = new DecimalFormat("0.0");
        String a = "0.0";
        try {
            a = format.format(new BigDecimal(price.replace(",", "")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }

    /**
     * 获取人民币符号
     */
    public static String getRMB() {
        return "¥";
    }

    /**
     * 判断手机号类型
     * <p>
     * 移动号段:
     * 134,135,136,137,138,139,147,148,150,151,152,157,158,159,172,178,182,183,184,
     * 187,188,198
     * <p>
     * 联通号段:
     * 130,131,132,145,146,155,156,166,171,175,176,185,186
     * <p>
     * 电信号段:
     * 133,149,153,173,174,177,180,181,189,199
     * <p>
     * 虚拟运营商:
     * 170
     *
     * @param phone
     * @return 0移动 1联通 2电信 3为虚拟号段 否则为其他号码
     */
    public static int PhoneNumberType(String phone) {

        int type;

        // 移动
        String CMCC = "(^1(3[4-9]|4[78]|5[0-27-9]|7[28]|8[2-478]|98)\\d{8}$)";
        // 联通
        String WCDMA = "(^1(3[0-2]|4[56]|5[56]|66|7[156]|8[56])\\d{8}$)";
        // 电信
        String CTWAP = "(^1(33|49|53|7[347]|8[019]|99)\\d{8}$)";

        String XU = "(^170\\d{8}$)";

        // 移动
        Pattern p1 = Pattern.compile(CMCC);
        Matcher m1 = p1.matcher(phone);

        // 联通
        Pattern p2 = Pattern.compile(WCDMA);
        Matcher m2 = p2.matcher(phone);

        // 电信
        Pattern p3 = Pattern.compile(CTWAP);
        Matcher m3 = p3.matcher(phone);

        // 虚拟号段
        Pattern p4 = Pattern.compile(XU);
        Matcher m4 = p4.matcher(phone);

        if (m1.matches()) {
            type = 0;// 移动
        } else if (m2.matches()) {
            type = 1;// 联通
        } else if (m3.matches()) {
            type = 2;// 电信
        } else if (m4.matches()) {
            type = 3;// 虚拟号段
        } else {
            type = 4;// 未知号码
        }
        return type;
    }

    public static String getPhoneType(int type) {
        String msg;
        switch (type) {
            case 0:
                msg = "中国移动";
                break;
            case 1:
                msg = "中国联通";
                break;
            case 2:
                msg = "中国电信";
                break;
            case 3:
                msg = "虚拟号段";
                break;
            case 4:
                msg = "未知号码";
                break;
            default:
                msg = "未知号码";
                break;
        }
        return msg;
    }

    /**
     * 生成随机密码
     *
     * @param len
     * @return
     */
    public static String getRandomNum(int len) {
        // 35是因为数组是从0开始的，26个字母+10个数字
        final int maxNum = 36;
        int i; // 生成的随机数
        int count = 0; // 生成的密码的长度
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer pwd = new StringBuffer();
        Random r = new Random();
        while (count < len) {
            // 生成随机数，取绝对值，防止生成负数，
            i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }

    /**
     * 获取sn号
     *
     * @return
     */
    public static String getDeviceSN() {
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                if (field.getName().equals("SERIAL")) {
                    field.setAccessible(true);
                    String SERIAL = field.get(null).toString();
                    return SERIAL;
                }
            } catch (Exception e) {
                LogUtils.i("an error occured when collect crash info", e);
                return "android";
            }
        }
        return "android";
    }

    /**
     * 字符串以空格隔开
     *
     * @param string
     * @param size   几个一组
     * @return
     */
    public static String getSplitGroup(String string, int size) {
        if (TextUtils.isEmpty(string))
            return "";
        StringBuilder sb = new StringBuilder(string);
        if (sb.length() > size) {
            for (int i = size; i < sb.length(); i += (size + 1)) {
                sb.insert(i, ' ');
            }
        }
        return sb.toString();
    }

    /**
     * 格式化身份证号码
     *
     * @param idCard
     * @return
     */
    public static String formatIdCard(String idCard) {
        if (TextUtils.isEmpty(idCard)) {
            return "0000";
        }
        return idCard.substring(0, 4) + "**********" + idCard.substring(idCard.length() - 4);
    }

    /**
     * 格式化银行卡号
     *
     * @param bankCard
     * @return
     */
    public static String formatBankCard(String bankCard) {
        if (TextUtils.isEmpty(bankCard)) {
            return "0000";
        }
        return bankCard.substring(0, 6) + "********" + bankCard.substring(bankCard.length() - 4);
    }

    /**
     * 格式化银行卡号
     *
     * @param cardNo
     * @return
     */
    public static String formatCardNo(String cardNo) {
        if (TextUtils.isEmpty(cardNo)) {
            return "0000";
        }
        return cardNo.substring(0, 4) + " **** **** " + cardNo.substring(cardNo.length() - 4);
    }

    /**
     * 格式化借款金额
     *
     * @param loanLimit
     * @return
     */
    public static String formatLoanLimit(String loanLimit) {
        if (TextUtils.isEmpty(loanLimit)) {
            return "0";
        }
        if (loanLimit.length() >= 5) {
            String start = loanLimit.substring(0, loanLimit.length() - 4);
            String end = loanLimit.substring(loanLimit.length() - 4);
            return start + "," + end;
        }

        return loanLimit;
    }

    /**
     * 格式化手机号码
     *
     * @param bindMobile
     * @return
     */
    public static String formatBindMobile(String bindMobile) {
//        if (TextUtils.isEmpty(bindMobile)) {
//            return "0000";
//        }
//        return bindMobile.substring(0, 3) + "****" + bindMobile.substring(bindMobile.length() - 4);
        if (!TextUtil.isEmpty(bindMobile) && bindMobile.matches(REGEX_NUMBER) && bindMobile.length() == 11){
            return bindMobile.substring(0, 3) + "****" + bindMobile.substring(bindMobile.length() - 4);
        }
        return bindMobile;
    }

    /**
     * 格式化Url
     *
     * @param url
     * @param s1
     * @param s2
     * @param ……
     * @return
     */
    public static String formatUrl(String url, String s1, int s2) {
        return String.format(url, s1, s2);
    }

    /**
     * 格式化用户名
     *
     * @param userName
     * @return
     */
    public static String getFormatUserName(String userName) {
        if (TextUtils.isEmpty(userName)) {
            return "用户*";
        }

        if (isMobile(userName)) {
            return userName.substring(0, 3) + "****" + userName.substring(userName.length() - 4);
        }

        if (userName.length() == 1) {
            return userName;
        }

        if (userName.length() == 2) {
            return userName.substring(0, 1) + "*";
        }

        return userName.substring(0, 1) + "****" + userName.substring(userName.length() - 1);

    }

    /*
     * 如果是小数，保留两位，非小数，保留整数
     * @param number
     */
    public static String getDoubleString(double number) {
        String numberStr;
        if (((int) number * 1000) == (int) (number * 1000)) {
            //如果是一个整数
            numberStr = String.valueOf((int) number);
        } else {
            DecimalFormat df = new DecimalFormat("######0.00");
            double parseDouble = Double.parseDouble(df.format(number));
            numberStr = String.valueOf(parseDouble);
        }
        return numberStr;
    }

    /*
     * 如果是小数，保留两位，非小数，保留整数
     * @param number
     */
    public static String getDoubleString(String numbers) {
        try {
            String numberStr;
            double number = Double.parseDouble(numbers);
            if (((int) number * 1000) == (int) (number * 1000)) {
                //如果是一个整数
                numberStr = String.valueOf((int) number);
            } else {
                DecimalFormat df = new DecimalFormat("######0.00");
                double parseDouble = Double.parseDouble(df.format(number));
                numberStr = String.valueOf(parseDouble);
            }
            return numberStr;
        } catch (NumberFormatException e) {
            return numbers;
        }
    }

}
